using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace IdPhotoAPIClient
{
    /// <summary>
    /// 证件照API客户端
    /// </summary>
    public class IdPhotoApiClient : IDisposable
    {
        private readonly HttpClient _httpClient;
        private readonly string _baseUrl;

        public IdPhotoApiClient(string baseUrl)
        {
            _baseUrl = baseUrl.TrimEnd('/');
            _httpClient = new HttpClient();
        }

        #region 1. 生成证件照(底透明)
        /// <summary>
        /// 生成证件照(底透明)
        /// </summary>
        public async Task<IdPhotoResponse> IdPhotoAsync(
            string imagePath,
            int height = 413,
            int width = 295,
            string humanMattingModel = "modnet_photographic_portrait_matting",
            string faceDetectModel = "mtcnn",
            bool hd = true,
            int dpi = 300,
            bool faceAlignment = true,
            float headMeasureRatio = 0.2f,
            float headHeightRatio = 0.45f,
            float topDistanceMax = 0.12f,
            float topDistanceMin = 0.1f,
            float brightnessStrength = 0,
            float contrastStrength = 0,
            float sharpenStrength = 0,
            float saturationStrength = 0)
        {
            var url = $"{_baseUrl}/idphoto";
            using var formData = new MultipartFormDataContent();

            // 添加文件
            var fileContent = new StreamContent(File.OpenRead(imagePath));
            formData.Add(fileContent, "input_image", Path.GetFileName(imagePath));

            // 添加其他参数
            formData.Add(new StringContent(height.ToString()), "height");
            formData.Add(new StringContent(width.ToString()), "width");
            formData.Add(new StringContent(humanMattingModel), "human_matting_model");
            formData.Add(new StringContent(faceDetectModel), "face_detect_model");
            formData.Add(new StringContent(hd.ToString().ToLower()), "hd");
            formData.Add(new StringContent(dpi.ToString()), "dpi");
            formData.Add(new StringContent(faceAlignment.ToString().ToLower()), "face_alignment");
            formData.Add(new StringContent(headMeasureRatio.ToString()), "head_measure_ratio");
            formData.Add(new StringContent(headHeightRatio.ToString()), "head_height_ratio");
            formData.Add(new StringContent(topDistanceMax.ToString()), "top_distance_max");
            formData.Add(new StringContent(topDistanceMin.ToString()), "top_distance_min");
            formData.Add(new StringContent(brightnessStrength.ToString()), "brightness_strength");
            formData.Add(new StringContent(contrastStrength.ToString()), "contrast_strength");
            formData.Add(new StringContent(sharpenStrength.ToString()), "sharpen_strength");
            formData.Add(new StringContent(saturationStrength.ToString()), "saturation_strength");

            var response = await _httpClient.PostAsync(url, formData);
            response.EnsureSuccessStatusCode();

            var jsonResponse = await response.Content.ReadAsStringAsync();
            var obj = JsonSerializer.Deserialize<IdPhotoResponse>(jsonResponse) ?? new IdPhotoResponse();

            return obj;
        }

        /// <summary>
        /// 生成证件照响应
        /// </summary>
        public class IdPhotoResponse
        {
            public bool status { get; set; }
            public string? image_base64 { get; set; }
            public string? image_base64_standard { get; set; }
            public string? image_base64_hd { get; set; }
        }
        #endregion

        #region 2. 添加背景色
        /// <summary>
        /// 添加背景色
        /// </summary>
        public async Task<IdPhotoResponse> AddBackgroundAsync(
            string imagePath,
            string color = "000000",
            int? kb = null,
            int render = 0,
            int dpi = 300)
        {
            var url = $"{_baseUrl}/add_background";
            using var formData = new MultipartFormDataContent();

            // 添加文件
            var fileContent = new StreamContent(File.OpenRead(imagePath));
            formData.Add(fileContent, "input_image", Path.GetFileName(imagePath));

            // 添加其他参数
            formData.Add(new StringContent(color), "color");
            formData.Add(new StringContent(render.ToString()), "render");
            formData.Add(new StringContent(dpi.ToString()), "dpi");

            if (kb.HasValue)
            {
                formData.Add(new StringContent(kb.Value.ToString()), "kb");
            }

            var response = await _httpClient.PostAsync(url, formData);
            response.EnsureSuccessStatusCode();

            var jsonResponse = await response.Content.ReadAsStringAsync();
            return JsonSerializer.Deserialize<IdPhotoResponse>(jsonResponse) ?? new IdPhotoResponse();
        }

        #endregion

        #region 3. 生成六寸排版照
        /// <summary>
        /// 生成六寸排版照
        /// </summary>
        public async Task<IdPhotoResponse> GenerateLayoutPhotosAsync(
            string imagePath,
            int height = 413,
            int width = 295,
            int? kb = null,
            int dpi = 300)
        {
            var url = $"{_baseUrl}/generate_layout_photos";
            using var formData = new MultipartFormDataContent();

            // 添加文件
            var fileContent = new StreamContent(File.OpenRead(imagePath));
            formData.Add(fileContent, "input_image", Path.GetFileName(imagePath));

            // 添加其他参数
            formData.Add(new StringContent(height.ToString()), "height");
            formData.Add(new StringContent(width.ToString()), "width");
            formData.Add(new StringContent(dpi.ToString()), "dpi");

            if (kb.HasValue)
            {
                formData.Add(new StringContent(kb.Value.ToString()), "kb");
            }

            var response = await _httpClient.PostAsync(url, formData);
            response.EnsureSuccessStatusCode();

            var jsonResponse = await response.Content.ReadAsStringAsync();
            return JsonSerializer.Deserialize<IdPhotoResponse>(jsonResponse) ?? new IdPhotoResponse();
        }

        #endregion

        #region 4. 人像抠图
        /// <summary>
        /// 人像抠图
        /// </summary>
        public async Task<IdPhotoResponse> HumanMattingAsync(
            string imagePath,
            string humanMattingModel = "modnet_photographic_portrait_matting",
            int dpi = 300)
        {
            var url = $"{_baseUrl}/human_matting";
            using var formData = new MultipartFormDataContent();

            // 添加文件
            var fileContent = new StreamContent(File.OpenRead(imagePath));
            formData.Add(fileContent, "input_image", Path.GetFileName(imagePath));

            // 添加其他参数
            formData.Add(new StringContent(humanMattingModel), "human_matting_model");
            formData.Add(new StringContent(dpi.ToString()), "dpi");

            var response = await _httpClient.PostAsync(url, formData);
            response.EnsureSuccessStatusCode();

            var jsonResponse = await response.Content.ReadAsStringAsync();
            return JsonSerializer.Deserialize<IdPhotoResponse>(jsonResponse) ?? new IdPhotoResponse();
        }

        #endregion

        #region 5. 图像加水印
        /// <summary>
        /// 图像加水印
        /// </summary>
        public async Task<IdPhotoResponse> WatermarkAsync(
            string imagePath,
            string text = "Hello",
            int size = 20,
            float opacity = 0.5f,
            int angle = 30,
            string color = "#000000",
            int space = 25,
            int dpi = 300)
        {
            var url = $"{_baseUrl}/watermark";

            // 构建查询参数
            var queryParams = new Dictionary<string, string>
            {
                ["size"] = size.ToString(),
                ["opacity"] = opacity.ToString(),
                ["angle"] = angle.ToString(),
                ["color"] = color,
                ["space"] = space.ToString()
            };

            var queryString = new StringBuilder();
            foreach (var param in queryParams)
            {
                if (queryString.Length > 0)
                    queryString.Append("&");
                queryString.Append($"{param.Key}={Uri.EscapeDataString(param.Value)}");
            }

            var fullUrl = $"{url}?{queryString}";

            using var formData = new MultipartFormDataContent();

            // 添加文件
            var fileContent = new StreamContent(File.OpenRead(imagePath));
            formData.Add(fileContent, "input_image", Path.GetFileName(imagePath));

            // 添加其他参数
            formData.Add(new StringContent(text), "text");
            formData.Add(new StringContent(dpi.ToString()), "dpi");

            var response = await _httpClient.PostAsync(fullUrl, formData);
            response.EnsureSuccessStatusCode();

            var jsonResponse = await response.Content.ReadAsStringAsync();
            return JsonSerializer.Deserialize<IdPhotoResponse>(jsonResponse) ?? new IdPhotoResponse();
        }

        #endregion

        #region 6. 设置图像KB大小
        /// <summary>
        /// 设置图像KB大小
        /// </summary>
        public async Task<IdPhotoResponse> SetKbAsync(
            string imagePath,
            int kb,
            int dpi = 300)
        {
            var url = $"{_baseUrl}/set_kb";
            using var formData = new MultipartFormDataContent();

            // 添加文件
            var fileContent = new StreamContent(File.OpenRead(imagePath));
            formData.Add(fileContent, "input_image", Path.GetFileName(imagePath));

            // 添加其他参数
            formData.Add(new StringContent(kb.ToString()), "kb");
            formData.Add(new StringContent(dpi.ToString()), "dpi");

            var response = await _httpClient.PostAsync(url, formData);
            response.EnsureSuccessStatusCode();

            var jsonResponse = await response.Content.ReadAsStringAsync();
            return JsonSerializer.Deserialize<IdPhotoResponse>(jsonResponse) ?? new IdPhotoResponse();
        }

        #endregion

        #region 7. 证件照裁切
        /// <summary>
        /// 证件照裁切
        /// </summary>
        public async Task<IdPhotoResponse> IdPhotoCropAsync(
            string imagePath,
            int height = 413,
            int width = 295,
            string faceDetectModel = "mtcnn",
            bool hd = true,
            int dpi = 300,
            float headMeasureRatio = 0.2f,
            float headHeightRatio = 0.45f,
            float topDistanceMax = 0.12f,
            float topDistanceMin = 0.1f)
        {
            var url = $"{_baseUrl}/idphoto_crop";
            using var formData = new MultipartFormDataContent();

            // 添加文件
            var fileContent = new StreamContent(File.OpenRead(imagePath));
            formData.Add(fileContent, "input_image", Path.GetFileName(imagePath));

            // 添加其他参数
            formData.Add(new StringContent(height.ToString()), "height");
            formData.Add(new StringContent(width.ToString()), "width");
            formData.Add(new StringContent(faceDetectModel), "face_detect_model");
            formData.Add(new StringContent(hd.ToString().ToLower()), "hd");
            formData.Add(new StringContent(dpi.ToString()), "dpi");
            formData.Add(new StringContent(headMeasureRatio.ToString()), "head_measure_ratio");
            formData.Add(new StringContent(headHeightRatio.ToString()), "head_height_ratio");
            formData.Add(new StringContent(topDistanceMax.ToString()), "top_distance_max");
            formData.Add(new StringContent(topDistanceMin.ToString()), "top_distance_min");

            var response = await _httpClient.PostAsync(url, formData);
            response.EnsureSuccessStatusCode();

            var jsonResponse = await response.Content.ReadAsStringAsync();
            return JsonSerializer.Deserialize<IdPhotoResponse>(jsonResponse) ?? new IdPhotoResponse();
        }

        #endregion

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}